<?php

namespace App\Http\Controllers\Admin\system;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Admin\CommonController;
use DB;
use App\User;
use App\Role,App\Permission;
use Route;
use Entrust;


class UserController extends CommonController
{

    public function __construct()
    {
        parent::__construct();
        view()->share([
            '_system' => 'active',
            '_user' => 'active',
//            'roles'=>Role::getroles(),
//            'permissions' => Permission::get_permissions()
        ]);
    }

    //显示用户管理界面
    public function index(Request $request)
    {
        //查找
        $where = function ($query) use ($request) {
            if ($request->has('keyword') and $request->keyword != '') {
                $search = "%" . $request->keyword . "%";
                $query->where('name', 'like', $search);
            }
        };

        $users=User::where($where)->whereHas('roles',function($query) use ($request){
            if ($request->has('role_id')) {
                $query->where('role_id', $request->role_id);
            }
        })->orderBy('id')->paginate(config('hwtc.page_size'));
        return view('admin.system.user.index')->with('users',$users);
    }


    //新增
    public function create()
    {
        return view('admin.system.user.create');
    }

    //存储
    public function store(Request $request){
        //验证提交数据是否规范
        $this->validate($request, [
            'name' => 'required|max:255|unique:users',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'role_id' => 'required',
        ]);
        $data=$request->all();
        $user=User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

        //给用户添加角色
        foreach($data['role_id'] as $id){
            $user->roles()->attach($id);
        }

        //或者
//        $role=Role::find($data['role_id']);
//        $user->attachRole($role);
        return redirect(route('system.user.index'))->with('success', '新增用户成功~');

    }

    public function edit($id){
        $user=User::with('roles')->find($id);
//        return $user->roles;
        return view('admin.system.user.edit')->with('user',$user);
    }

    //更新
    public function update(Request $request,$id){

        //验证提交数据是否规范
        $this->validate($request, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255',
            'password' => 'required|min:6',
            'role_id' => 'required',
        ]);
        $data=$request->all();
        $user=User::find($id);
        if($user->password!=$data['password']){
            $user->update([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password'])
            ]);
        }else{
            $user->update([
                'name' => $data['name'],
                'email' => $data['email']
            ]);
        };

        //更新用户角色！
        $user->roles()->detach();  //先删除该用户所有角色
        foreach($data['role_id'] as $id){
            $user->roles()->attach($id);
        }
        return redirect(route('system.user.index'))->with('success', '编辑用户成功~');
    }

    //删除
    public function destroy($id){
        $user=User::find($id);
        DB::beginTransaction();
        try{
            $user->roles()->detach();
            User::destroy($id);
        }catch(\Exception $e){
            DB::rollback();
            return $e->getMessage();
        }

        return redirect(route('system.user.index'))->with('success', '删除用户成功~');
    }

}
